import 'dart:async';
import 'package:animated_bottom_navigation_bar/animated_bottom_navigation_bar.dart';
import 'package:animations/animations.dart';
import 'package:auto_size_text/auto_size_text.dart';
import 'package:common_utils/common_utils.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:part_time_job_pro/common/index.dart';
import 'package:part_time_job_pro/pages/home/index.dart';
import 'package:part_time_job_pro/pages/offer/proxy/view.dart';
import 'package:part_time_job_pro/pages/public/full/view.dart';
import 'package:part_time_job_pro/pages/public/part/view.dart';
import 'package:part_time_job_pro/pages/public/school/view.dart';

class HomePage extends StatelessWidget {
  HomePage({Key? key}) : super(key: key);

  //路由地址
  final logic = Get.find<HomeLogic>();
  final state = Get.find<HomeLogic>().state;

  @override
  Widget build(BuildContext context) {
    return GetBuilder<HomeLogic>(
      init: HomeLogic(),
      builder: (logic) => Scaffold(
        extendBody: true,
        backgroundColor: const Color.fromARGB(255, 224, 223, 223),
        body: PageTransitionSwitcher(
          transitionBuilder: (child, animation, secondaryAnimation) {
            return FadeThroughTransition(animation: animation, secondaryAnimation: secondaryAnimation, child: child);
          },
          child: state.mainIndexStackPages[state.currentIndex],
        ),
        floatingActionButton: FloatingActionButton(
          foregroundColor: AppColor.accentColor,
          backgroundColor: AppColor.norMainThemeColors,
          elevation: 2,
          shape: const CircleBorder(side: BorderSide(color: AppColor.norMainThemeColors, width: 1)),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              const Icon(Icons.add, color: AppColor.norWhite01Color),
              Text(
                "发布",
                style: TextStyle(fontSize: 11.r, color: Colors.white),
              ),
            ],
          ),
          onPressed: () {
            //弹出窗口
            showPublicOfferWidget(context);
          },
        ),
        floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
        bottomNavigationBar: AnimatedBottomNavigationBar.builder(
          elevation: 0,
          itemCount: state.iconList.length,
          tabBuilder: (int index, bool isActive) {
            final color = isActive ? AppColor.norMainThemeColors : AppColor.norGray04Color;
            return Padding(
              padding: const EdgeInsets.only(top: 4),
              child: Column(
                mainAxisSize: MainAxisSize.min,
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Image.asset(
                    isActive
                        ? "${AssetsImages.iconPath}/icon_${state.iconList[index]}_selected.png"
                        : "${AssetsImages.iconPath}/icon_${state.iconList[index]}.png",
                    width: 18.sp,
                    height: 18.sp,
                    gaplessPlayback: true,
                  ),
                  const SizedBox(height: 4),
                  Padding(
                    padding: const EdgeInsets.symmetric(horizontal: 8),
                    child: AutoSizeText(
                      logic.getTranslatedLabel(index),
                      maxLines: 1,
                      style: TextStyle(color: color, fontSize: 12.r),
                      group: logic.autoSizeGroup,
                    ),
                  ),
                ],
              ),
            );
          },
          backgroundColor: AppColor.norGray01Color,
          activeIndex: state.currentIndex,
          splashColor: AppColor.norMainThemeColors,
          notchAndCornersAnimation: logic.borderRadiusAnimation,
          splashSpeedInMilliseconds: 300,
          notchSmoothness: NotchSmoothness.defaultEdge,
          hideAnimationController: logic.hideBottomBarAnimationController,
          gapLocation: GapLocation.center,
          leftCornerRadius: 0,
          rightCornerRadius: 0,
          onTap: (index) async {
            logic.changSelectedIndex(index);
          },
          shadow: BoxShadow(
            offset: const Offset(0, 1),
            blurRadius: 5.r,
            spreadRadius: .5.r,
            color: AppColor.norGray02Color,
          ),
        ),
      ),
    );
  }

  ///弹出发布
  showPublicOfferWidget(BuildContext context) {
    showModalBottomSheet(
      context: context,
      backgroundColor: Colors.transparent,
      builder: (context) => GetBuilder<HomeLogic>(
        id: "bottomPubSheet",
        builder: (logic) => Container(
          color: Colors.transparent,
          //height: 500.r,
          width: 1.sw,
          child: Column(
            mainAxisAlignment: MainAxisAlignment.start,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Padding(
                padding: EdgeInsets.only(left: 15.w, right: 15.w),
                child: Stack(
                  children: [
                    Image.asset(AssetsImages.publicBack, fit: BoxFit.fill),
                    Positioned(
                      right: 13.r,
                      top: 15.r,
                      child: InkWell(
                        child: Text(
                          "申请代招服务 >",
                          style: TextStyle(
                            fontSize: 12.r,
                            fontWeight: FontWeight.normal,
                            color: AppColor.norBlue01Colors,
                          ),
                        ),
                        onTap: () {
                          Get.offAndToNamed(ProxyPage.routeName);
                        },
                      ),
                    ),
                    Positioned(
                      top: 45.r,
                      left: 20.r,
                      child: SafeArea(
                        child: Container(
                          padding: EdgeInsets.all(5.r),
                          height: 120.r,
                          width: 1.sw - 70.r,
                          color: Colors.white,
                          child: Scrollbar(
                            controller: logic.scrollController,
                            thickness: state.scrollBarThickness,
                            thumbVisibility: true,
                            trackVisibility: true,
                            child: GestureDetector(
                              onTap: () {
                                //延迟隐藏
                                Future.delayed(const Duration(seconds: 3), () {
                                  state.scrollBarThickness = 0.0;
                                  logic.update();
                                });
                              },
                              child: SingleChildScrollView(
                                controller: logic.scrollController,
                                child: AutoSizeText.rich(
                                  TextSpan(
                                    children: [
                                      TextSpan(
                                        text:
                                            "发布千万条，诚实第一条，招聘不规范，处罚两行泪！\n另：个别情况可能须进一步提供企业官网、官博、官微、工牌、名片、公司门面照、代招协议等证明材料。\n",
                                        style: TextStyle(
                                          fontSize: 12.r,
                                          fontWeight: FontWeight.normal,
                                          color: AppColor.norGray04Color,
                                        ),
                                      ),
                                      TextSpan(
                                        text: "\n禁止发布以下内容：\n",
                                        style: TextStyle(
                                          fontSize: 12.r,
                                          fontWeight: FontWeight.normal,
                                          color: AppColor.norGray04Color,
                                        ),
                                      ),
                                      TextSpan(
                                        text: "跨境/外地出差工作、招工代理、游戏代练、代课、充场、替考、手工活、人体试验、卖血卖精、刷单、收费会员制兼职等。其他视实际情况判断\n",
                                        style: TextStyle(
                                          fontSize: 12.r,
                                          fontWeight: FontWeight.normal,
                                          color: AppColor.norGray04Color,
                                        ),
                                      ),
                                      TextSpan(
                                        text: "注意！涉及普工、物流、教育行业类工作，须为“企业机构”认证发布。其他视实际情况判断要求。（完成“企业机构”认证，招聘效果会更棒哦~）\n",
                                        style: TextStyle(
                                          fontSize: 12.r,
                                          fontWeight: FontWeight.normal,
                                          color: AppColor.norGray04Color,
                                        ),
                                      ),
                                      TextSpan(
                                        text: "\n请联系业务部门：\n",
                                        style: TextStyle(
                                          fontSize: 12.r,
                                          fontWeight: FontWeight.normal,
                                          color: AppColor.norGray04Color,
                                        ),
                                      ),
                                      TextSpan(
                                        text:
                                            "试玩、淘客、短视频带货类、朋友圈转发点赞、闲鱼/淘宝天猫开店/代理类销售、主播/陪聊/拍手/模特/录音相关/图文标注（甲方直招）、网约车司机（企业机构）等，请联系业务部门洽谈合作。\n",
                                        style: TextStyle(
                                          fontSize: 12.r,
                                          fontWeight: FontWeight.normal,
                                          color: AppColor.norGray04Color,
                                        ),
                                      ),
                                    ],
                                  ),
                                  softWrap: true,
                                ),
                              ),
                            ),
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
              SizedBox(height: 10.r),
              Flexible(
                fit: FlexFit.loose,
                child: Container(
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.only(topLeft: Radius.circular(10.r), topRight: Radius.circular(10.r)),
                    color: Colors.white,
                  ),
                  width: 1.sw,
                  child: Stack(
                    fit: StackFit.expand,
                    children: [
                      AnimatedPositioned(
                        duration: const Duration(milliseconds: 200),
                        top: state.ishowModal ? 15.h : 100.h,
                        left: 0,
                        curve: Curves.easeInOut,
                        child: buildPublicBtnWidget(0),
                      ),
                      AnimatedPositioned(
                        duration: const Duration(milliseconds: 300),
                        top: state.ishowModal ? 15.h : 100.h,
                        left: 1.sw / 3,
                        curve: Curves.easeInOut,
                        child: buildPublicBtnWidget(1),
                      ),
                      AnimatedPositioned(
                        duration: const Duration(milliseconds: 400),
                        top: state.ishowModal ? 15.h : 100.h,
                        right: 0,
                        curve: Curves.easeInOut,
                        child: buildPublicBtnWidget(2),
                      ),
                      AnimatedPositioned(
                        duration: const Duration(milliseconds: 450),
                        top: state.ishowModal ? 140.h : 220.h,
                        right: 0,
                        curve: Curves.easeInOut,
                        child: buildModalCloseBtn(),
                      ),
                    ],
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    ).then((value) {
      state.ishowModal = false;
    });

    Future.delayed(const Duration(milliseconds: 100), () => logic.updateModalData());
  }

  Widget buildModalCloseBtn() {
    return GestureDetector(
      onTap: () {
        state.ishowModal = false;
        Get.back();
      },
      child: Container(
        color: Colors.white,
        width: 1.sw,
        child: Container(
          constraints: BoxConstraints(maxHeight: 32.r, maxWidth: 32.r),
          child: Image.asset(AssetsImages.publicCloseBtn, height: 32.r, width: 32.r),
        ),
      ),
    );
  }

  //发布按钮
  Widget buildPublicBtnWidget(index) {
    var item = state.publicTypeList[index];
    return GestureDetector(
      onTap: () {
        if (index == 0) {
          //兼职
          LogUtil.e("兼职");
          Get.offAndToNamed(PartJobPage.routeName);
          //Get.toNamed(page);
        } else if (index == 1) {
          //全职
          LogUtil.e("全职");
          Get.offAndToNamed(FullJobPage.routeName);
          //Get.toNamed(page);
        } else {
          //校招
          LogUtil.e("校招");
          Get.offAndToNamed(SchoolJobPage.routeName);
          //Get.toNamed(page);
        }
      },
      child: Container(
        color: Colors.white,
        margin: EdgeInsets.symmetric(horizontal: 5.r),
        width: 1.sw / 3,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            SizedBox(height: 10.r),
            Image.asset("${item["icon"]}", height: 64.r, width: 64.r),
            Text(
              "${item["name"]}",
              style: TextStyle(fontSize: 12.r, fontWeight: FontWeight.normal, color: AppColor.norBlackColors),
            ),
            Text(
              "剩余${item["count"]}次",
              style: TextStyle(fontSize: 11.r, fontWeight: FontWeight.normal, color: AppColor.norMainThemeColors),
            ),
          ],
        ),
      ),
    );
  }
}
